#include "YAvi.h"
extern "C"
{
    #include "avilib.h"
}
#include <QUuid>
#include <QDir>
#include <QFileInfo>
#include <QBuffer>

#define OUTFD reinterpret_cast<avi_t*>(outFd)

#include "MediaCommon.h"

YAvi::YAvi(QObject *parent) : YMedia(parent)
{}

YAvi::~YAvi()
{
    if(isOpen()){
        close();
    }
}

bool YAvi::open()
{
    setTempFileName();

    char* cFileName = MediaCommon::QStringToChars(tempFileName);
    avi_t* t_out_fd = AVI_open_output_file(cFileName);
    delete [] cFileName;
    if(t_out_fd){
        outFd = reinterpret_cast<quintptr>(t_out_fd);
        isOpened = true;
        return true;
    }
    tempFileName.clear();
    return false;
}

void YAvi::setVideo(int width, int height, double fps, const QString& extra)
{
    if(!isOpen()) return;
    char* cCompressor = MediaCommon::QStringToChars(extra);
    AVI_set_video(OUTFD, width, height, fps, cCompressor);
    delete [] cCompressor;
}

void YAvi::addFrame(const QImage &frame)
{
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    frame.save(&buffer, "jpg", 100);
    buffer.close();
    if(notFirstFrame){
        AVI_write_frame(OUTFD, byteArray.data(), byteArray.size(), 0);
    }else{
        AVI_write_frame(OUTFD, byteArray.data(), byteArray.size(), 1);
        notFirstFrame = true;
    }
}

void YAvi::setRadio(int channels, long rate, int bits, int format, long mp3rate)
{
    if(isOpen()) return;

    AVI_set_audio(OUTFD, channels, rate, bits, format, mp3rate);
}

int YAvi::close()
{
    if(isOpened){
        isOpened = false;
        return AVI_close(OUTFD);
    }
    return 0;
}

bool YAvi::save(const QString &outputFileName)
{
    if(tempFileName.isEmpty()) return false;
    if(isOpen()){
        close();
    }

    bool ret = QFile(tempFileName).copy(outputFileName);
    QFile::remove(tempFileName);
    return ret;
}

QString YAvi::saveFileType()
{
    return "AVI视频(*.avi)";
}

#include <QFileDialog>
QString YAvi::defaultFileDialog()
{
    return QFileDialog::getSaveFileName(nullptr, "保存", "D:/Temp/未命名.avi", "AVI视频(*.avi)");
}
